from content.models import KeywordDB
from content.models import LinkDB
from content.models import ContentDB

from content.models import save_content, save_keywords, save_links
from content.keyextract.keywords_extraction import extract_keywords
from content.contprov.content_providers import ask_content_providers

result_groups = [];
class Keyword:
	def __init__(self, priority, keyword):
		self.priority = priority
		self.keyword = keyword
	def __unicode__(self):
		return self.keyword

class Link:
	def __init__(self, priority, link, group):
		self.priority = priority
		self.link = link
		self.group = group
	def __unicode__(self):
		return self.link+self.group

class OneLink:
	def __init__(self, url, description):
		self.url = url
		self.description = description
	def __unicode__(self):
		return self.url
		
def get_keywords_by_id(id):
	keyList = KeywordDB.objects.filter(idUser=id)
	list = []
	for k in keyList:
		if k.deleted == 'n': 
			list.append(k)
			print k
	return adapt_keywords(list)

def get_links_by_id(id):
	groupList = LinkDB.objects.filter(idUser=id)
	return adapt_links(groupList)

def adapt_keywords(keywords):
	keyList = []
	for k in keywords:
		key = Keyword(k.priority,k.keyword)
		keyList.append(key)
	return keyList

def adapt_links(links):
	list = []
	groups = {}
	for l in links:
		try:
			groups[l.group]
			fake = OneLink(url=l.link, description=l.description)
			groups[l.group].append(fake)
		except KeyError: 
			fake = OneLink(url=l.link, description=l.description)
			groups[l.group] = [fake]
	i = 1;
	for (k, v) in groups.iteritems():
		link = Link(i,v,k)
		list.append(link)
		i += 1
	return list


def create_example_links():
	linkList = []
	i = 1
	while i < 6:
		links = []
		j = 1
		while j < 3:
			name = "link"+str(i)+str(j)
			links.append(name)
			j+=1
		link = Link(i,links,"group"+str(i))
		linkList.append(link)
		i+=1
	return linkList
	
def create_example_keywords():
	keywordList = []
	i = 1
	while i < 6:
		keyword = Keyword(i,"keyword"+str(i))
		keywordList.append(keyword)
		i+=1
	return keywordList

def update_content(id, content):
	id = save_content(id,content)
	keywords = extract_keywords(content)
	#printAllKeywords(id)
	save_keywords(id, keywords)
	refresh_links(id)
	return id

def refresh_links(id):
	links = ask_content_providers(get_keywords_by_id(id))
	save_links(id, links)

def get_group_links(id,group):
	list = LinkDB.objects.filter(idUser=id,group=group)
	return list
